package com.cat.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cat.common.entity.*;
import com.cat.admin.mapper.SysUserMapper;
import com.cat.admin.service.SysUserService;
import com.cat.admin.service.SysMenuService;
import com.cat.admin.service.SysRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author dd-cat
 * @version 1.0
 * @date 2020-10-13 14:21
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysRoleService sysRoleService;
    private final SysMenuService sysMenuService;

    /**
     * 通过查用户的全部信息
     *
     * @param user 用户
     * @return UserInfo
     */
    @Override
    public UserInfo getUserInfo(SysUser user) {
        Set<String> permissions = new HashSet<>();
        List<Long> roleIds = sysRoleService.findRolesByUserId(user.getId()).stream().map(SysRole::getId)
                .collect(Collectors.toList());
        if (user.getIsAdmin()) {
            permissions.add("admin");
            List<GrantedAuthority> collect = permissions.stream().map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
            return new UserInfo(user, roleIds, collect);
        }
        roleIds.forEach(roleId -> {
            List<String> permissionList = sysMenuService.findMenuByRoleId(roleId).stream()
                    .filter(menu -> StrUtil.isNotEmpty(menu.getPermission())).map(SysMenu::getPermission)
                    .collect(Collectors.toList());
            permissions.addAll(permissionList);
        });
        List<GrantedAuthority> collect = permissions.stream().map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return new UserInfo(user, roleIds, collect);
    }

}
